<template>
  <div
    id="editor"
    class="editor"
    :class="{ edit: isEdit }"
    :style="{
      width: changeStyleWithScale(canvasStyleData.width) + 'px',
      height: changeStyleWithScale(canvasStyleData.height) + 'px',
      background: canvasStyleData.backgroundColor,
    }"
    @mousedown="handleMouseDown"
  >
    <Shape
      v-for="(item, index) in componentData"
      :style="getShapeStyle(item.style)"
      :key="item.id"
      :element="item"
      :index="index"
      :defaultStyle="item.style"
      :active="item.id === (curComponent || {}).id"
    >
      <component
        :is="item.component"
        v-if="item.component != 'v-text'"
        :id="'component' + item.id"
        class="component"
        :style="getComponentStyle(item.style)"
        :prop-value="item.propValue"
        :element="item"
      />

      <component
        :is="item.component"
        v-else
        :id="'component' + item.id"
        class="component"
        :style="getComponentStyle(item.style)"
        :prop-value="item.propValue"
        :element="item"
        @input="handleInput"
      />
    </Shape>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { getStyle } from "@/utils/style";
import { changeStyleWithScale } from "@/utils/translate.js";
import Shape from "./Shape";
export default {
  components: {
    Shape,
  },
  props: {
    isEdit: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {};
  },
  computed: mapState([
    "componentData",
    "canvasStyleData",
    "curComponent",
    "editor",
  ]),
  mounted() {
    // 获取编辑器元素
    this.$store.commit("getEditor");
  },

  methods: {
    changeStyleWithScale,
    handleMouseDown() {},
    handleInput(element, value) {
      // 根据文本组件高度调整 shape 高度
      this.$store.commit("setShapeStyle", {
        height: this.getTextareaHeight(element, value),
      });
    },

    getTextareaHeight(element, text) {
      let { lineHeight, fontSize, height } = element.style;
      if (lineHeight === "") {
        lineHeight = 1.5;
      }

      const newHeight = (text.split("<br>").length - 1) * lineHeight * fontSize;
      return height > newHeight ? height : newHeight;
    },
    getShapeStyle(style) {
      const result = {};
      ["width", "height", "top", "left", "rotate"].forEach((attr) => {
        if (attr != "rotate") {
          result[attr] = style[attr] + "px";
        } else {
          result.transform = "rotate(" + style[attr] + "deg)";
        }
      });

      return result;
    },
    getComponentStyle(style) {
      return getStyle(style, ["top", "left", "width", "height", "rotate"]);
    },
  },
};
</script>
<style lang="less">
.editor {
  position: relative;
  background: #fff;
  margin: auto;

  .lock {
    opacity: 0.5;

    &:hover {
      cursor: not-allowed;
    }
  }
}

.edit {
  .component {
    outline: none;
    width: 100%;
    height: 100%;
  }
}
</style>
